package org.hepeng.workx.spring.cloud.netflix.zuul.route;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.Route;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author he peng
 */

@Slf4j
public class ContextPathZuulRoutingRewriteMatch extends AbstractZuulRoutingRewriteMatch {


    public ContextPathZuulRoutingRewriteMatch(HttpServletRequest request, String originalUri, List<Route> routes) {
        super(request, originalUri, routes);
    }

    @Override
    protected boolean matchRoute(Route route, String appId) {
        String prefixName = StringUtils.replace(route.getPrefix(), "/", "");
        if (StringUtils.isNotBlank(appId)
                && ! StringUtils.equals(prefixName , appId)
                && StringUtils.endsWithIgnoreCase(route.getId() , appId)) {

            super.request.setAttribute(REWRITE_MATCH_CLASS_REQUEST_ATTR, this.getClass().getName());
            return true;
        }
        return false;
    }

    @Override
    protected String getApplicationId() {
        return getContextPathName();
    }

    private String getContextPathName() {
        String contextPathName = null;
        String requestUri = super.originalUri;
        String contextPath = super.request.getServletContext().getContextPath();
        if (StringUtils.startsWith(requestUri , contextPath)) {
            requestUri = StringUtils.removeFirst(requestUri , contextPath);
        }
        int beginIndex = StringUtils.indexOf(requestUri, "/");
        if (beginIndex != -1) {
            beginIndex += 1;
        }
        String subRequestUri = StringUtils.substring(requestUri, beginIndex);
        int endIndex = StringUtils.indexOf(subRequestUri , "/");
        if (endIndex != -1) {
            endIndex += 1;
        }

        if (beginIndex == -1 && endIndex != -1) {
            contextPathName = StringUtils.substring(requestUri , 0 , endIndex);
        } else if (beginIndex != -1 && endIndex == -1) {
            contextPathName = StringUtils.substring(requestUri , beginIndex);
        } else if (beginIndex == -1 && endIndex == -1) {
            contextPathName = requestUri;
        } else if(endIndex != -1 && endIndex != -1) {
            contextPathName = StringUtils.substring(requestUri , beginIndex , endIndex);
        }
        return contextPathName;
    }
}
